package com.ta.gulimall.auth.service.impl;

import cn.hutool.core.lang.TypeReference;
import com.ta.gulimall.common.constant.AuthConstant;
import com.ta.gulimall.common.utils.RandomUtils;
import com.ta.gulimall.common.utils.system.R;
import com.ta.gulimall.common.utils.RedisUtil;
import com.ta.gulimall.auth.constant.AuthRedisKeyConstant;
import com.ta.gulimall.auth.feign.MemberFeignService;
import com.ta.gulimall.auth.feign.ThirdPartyFeignService;
import com.ta.gulimall.auth.service.RegisterService;
import com.ta.gulimall.common.view.vo.MemberVo;
import com.ta.gulimall.auth.view.vo.UserLoginVo;
import com.ta.gulimall.auth.view.vo.UserRegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

@Service
public class RegisterServiceImpl implements RegisterService {
    @Autowired
    ThirdPartyFeignService thirdPartyFeignService;
    @Autowired
    RedisUtil redisUtil;

    @Autowired
    MemberFeignService memberFeignService;

    @Override
    public void sendCode(String phone) {
        Object sendCode = redisUtil.get(AuthRedisKeyConstant.PHONE_SECURITY_CODE_SEND + "_" + phone);
        if (sendCode != null) {
            throw new RuntimeException("请求太频繁，请稍后再试");
        }

        String code = RandomUtils.GenerateAuthCode();
        R result = thirdPartyFeignService.sendCode(phone, Integer.parseInt(code));
        if (!result.getCode().equals("0")) {
            throw new RuntimeException(result.getMsg());
        }
        //设置有效期
        redisUtil.set(AuthRedisKeyConstant.SECURITY_CODE + "_" + phone, code, 60 * 5);
        //验证码防刷key
        redisUtil.set(AuthRedisKeyConstant.PHONE_SECURITY_CODE_SEND + "_" + phone, code, 60);
    }

    @Override
    public void register(UserRegisterVo vo) {
        Object redisCode = redisUtil.get(AuthRedisKeyConstant.SECURITY_CODE + "_" + vo.getPhone());
        if (redisCode == null) {
            throw new RuntimeException("验证码已过期");
        }

        if (!vo.getCode().equals(redisCode)) {
            throw new RuntimeException("验证码不正确");
        }

        redisUtil.del(AuthRedisKeyConstant.SECURITY_CODE + "_" + vo.getPhone());
        R result = memberFeignService.register(vo);

        if (!result.getCode().equals("0")) {
            throw new RuntimeException(result.getMsg());
        }
    }
}













